<?php
/**
 * Created by PhpStorm.
 * User: joe
 * Date: 17-12-2
 * Time: 下午1:57
 */

namespace App\Models;

use \System\Model;

class Category extends Model
{
    protected $table = "category";
    protected $id = 'id';
    protected $fields = ['id', 'name', 'parent'];

    protected function buildTree($items, $parent = 0, $ckey = 'children')
    {
        $tree = array();
        foreach ($items as $rk => $rv) {
            if ($rv['parent'] == $parent) {
                $children = $this->buildTree($items, $rv['id']);
                if ($children) {
                    $rv[$ckey] = $children;
                }
                $tree[] = $rv;
            }
        }
        return $tree;
    }

    public function jsonTree($id = 0, $childKey = 'children')
    {
        return $this->buildTree($this->getChildren($id), $id, $childKey);
    }

    public function getChildren($id, $select = '*', $self = true)
    {
        $sql = "select {$select} from ( select t1.*, if(find_in_set(parent, @pids) > 0, @pids := concat(@pids, ',', t1.id), 0) as ischild from ( select * from category t order by parent, id ) t1, (select @pids := {$id}) t2 ) t3 where ischild != 0 ";
        $sql .= $self ? " OR id={$id}" : '';

        $children = $this->db->query($sql)->result();

        if (strtolower($select) == "id") {
            $child = [];
            foreach ($children as $c) {
                $child[] = $c['id'];
            }
            return $child;
        }

        return $children;
    }

    public function getParents($id, $clear = true)
    {
        if ($clear) {
            $this->parents = [];
        }
        if ($id) {
            $city = $this->find($id);
            $this->parents[] = $city;
            $this->getParents($city['parent'], false);
        }
        return $this->parents;
    }

    public function deleteAll($id, $children = true)
    {
        $ids = $children ? $this->getChildren($id, 'id') : $id;
        $this->where('id', $ids, "in")->delete();
    }
}